import { getUrlParam } from 'src/boot/paramhandler';
import { readonly, ref } from 'vue';
import { getRouter } from 'src/router/index';
import { RouteLocationNormalizedLoadedGeneric } from 'vue-router';
const router = getRouter();
const isMiniprogram = ref(false);

(window as any).wx.miniProgram.getEnv(function (res: { miniprogram: boolean }) {
  isMiniprogram.value = res.miniprogram;
});

const toWxMiniGZH = () => {
  (window as any).wx.miniProgram.redirectTo({url: '/pages/gzh/gzh'})
}

const toWxWebview= (url: string, isGetLocal: boolean) => {
  (window as any).wx.miniProgram.redirectTo({url: `/pages/webview/webview?url=${encodeURIComponent(url)}${isGetLocal ? '&isGetLocal=1' : ''}`})
}

const isAnyirongMini = () => {
  if (isMiniprogram.value) return true;
  const { param } = getUrlParam()
  return !!param.isWxMini
}


const getLocal = () => {
  return new Promise<any>((resovle, resject) => {
    (window as any).wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res: any) {
        resovle(res)
        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
        var speed = res.speed; // 速度，以米/每秒计
        var accuracy = res.accuracy; // 位置精度
      }
    });
  })
}
const gotoEvaluteFaill = (route: RouteLocationNormalizedLoadedGeneric) => {
  if(isMiniprogram.value){
    router.push({ path: '/evaluateAuth', query: { ...route.query, isFail: 1 } });
  }else{
    router.push({ path: '/shop', query: { ...route.query, isFail: 1 } });
  }
}
const gotoEvaluteSuccess = (route: RouteLocationNormalizedLoadedGeneric) => {
  if(isMiniprogram.value){
    router.push({ path: '/evaluateAuth', query: { ...route.query, isFail: 0 } });
  }else{
    router.replace({ path: '/shop', query: { ...route.query, isFail: 0 } });
  }
}
export const useWxHook = () => {
  return {
    isMiniprogram: readonly(isMiniprogram),
    toWxMiniGZH,
    getLocal,
    toWxWebview,
    isAnyirongMini,
    gotoEvaluteFaill,
    gotoEvaluteSuccess
  }
}
